package com.example.user.service;

import com.example.user.dao.UserMapper;
import com.example.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 8:52 2019/4/3
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public User login(User user) {
      User currentUser=userMapper.selectUserByUsername(user.getUsername());
        if (passwordEncoder.matches(user.getPassword(),currentUser.getPassword())){
            return currentUser;
        }else {
            return null;
        }
    }

    @Override
    public void register(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
    }

    @Override
    public User editInfo(User user) {
       User currentUser=userMapper.selectByPrimaryKey(user.getId());
       if (passwordEncoder.matches(user.getPassword(),currentUser.getPassword())){
              currentUser.setPassword(passwordEncoder.encode(user.getNewPassword()));
              userMapper.updateByPrimaryKeySelective(currentUser);
              return currentUser;
       }else {
           return null;
       }

    }
}
